<?php

require_once(realpath(dirname(__FILE__)) . "/parseur/PexElement.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/PexTexte.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/PexToken.interface.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/Analyse.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/BoucleConditionnelle.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/BoucleConditionnelleVariable.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/BoucleRepeter.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/BoucleSimple.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/BoucleTest.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/ContenuElement.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/EvalBoucle.class.php");
require_once(realpath(dirname(__FILE__)) . "/parseur/IterationBoucle.class.php");


// Pour les tests uniquement
// error_reporting(E_ALL);

class Parseur
{
	const PREFIXE   = 'prx';

	const SHOW_TIME = true;
	const ALLOW_DEBUG = true;
	const USE_CACHE = true;

	private static $parse_time;

	private $vars = array();

	protected $cache_dir;

    static $VARIABLES_CONDITIONNELLES = array('PROMO', 'NOUVEAU');

	function __construct(){

		$this->cache_dir = realpath(dirname(__FILE__)) . '/../client/cache/parseur/';

        // Date de dernier examen du cache (en secondes)
        self::create_variable(self::PREFIXE.'_cache_check_time', 0);
	}

	function analyse($res){
		$time_start = $this->microtime_float();
		$res = $this->parse_text($res);
		self::$parse_time = $this->microtime_float() - $time_start;

		return $res;
	}

	function set_var($variable, $valeur)
	{
		$this->vars['#'.$variable] = $valeur;
	}

	public static function ajouter_variable_conditionnelle($nom)
	{
		self::$VARIABLES_CONDITIONNELLES[] = $nom;
	}

	function parse_text($texte){
		// substitution variables internes
		if (count($this->vars) > 0)
			$texte = str_replace(array_keys($this->vars), array_values($this->vars), $texte);

		// substition simples
		$texte = substitutions($texte);

		// laisser les infos pour les connectÃ©s ou non connectÃ©s
		$texte = $this->filtre_connecte($texte);

		// traitement dans le cas d'un formulaire
		if(isset($_GET['errform']) && $_GET['errform'] == "1") $texte = $this->traitement_formulaire($texte);

		$parseur = new Analyse(self::get_variable(self::PREFIXE.'_allow_debug'));

	    $contenu = self::get_variable(self::PREFIXE.'_use_cache') ? $parseur->parse_string_with_cache($texte, $this->cache_dir) : $parseur->parse_string($texte);

	    $texte = $contenu->evaluer();

	    $parseur->terminer();

	    return $texte;
	}

	// Inclusions

	function inclusion($lect){

		$res = "";
		$i =0;

		while($i<count($lect)) {

				$rec = $lect[$i++];

   			    if(strstr($rec, "#INCLURE")){

					if (preg_match("/\"([^\"]*)\"/", "$rec", $cut)) {
						$fichier = $cut[1];

						if(!file_exists($fichier)) { echo "Impossible d'ouvrir le fichier inclus $fichier"; exit; }
						$res .= $this->inclusion(explode("\n",file_get_contents($fichier)));

						$res .= "\n";
					}
				}

				else $res .= $rec . "\n";

		}

		return $res;
	}


	// filtre si connecte
	function filtre_connecte($lect){

		// rÃ©cupÃ¨re les infos
			if($_SESSION['navig']->connecte){

				$lect = preg_replace("|<THELIA SI CONNECTE>(.*)</THELIA SI CONNECTE>|Us", "\\1", $lect);
				$lect = preg_replace("|<THELIA SI NON CONNECTE>.*</THELIA SI NON CONNECTE>|Us", "", $lect);

			}

			else if(! $_SESSION['navig']->connecte){

				$lect = preg_replace("|<THELIA SI CONNECTE>.*</THELIA SI CONNECTE>|Us", "", $lect);
				$lect = preg_replace("|<THELIA SI NON CONNECTE>(.*)</THELIA SI NON CONNECTE>|Us", "\\1", $lect);
			}


		return $lect;

	}

	function traitement_formulaire($res){

        if($_SESSION['navig']->formcli->email !=""){
                 $client = new Client();
                 if( $client->existe($_SESSION['navig']->formcli->email)) $res = preg_replace("/\#EXISTE\[([^]]*)\]/", "\\1", $res);
                 else $res = preg_replace("/\#EXISTE\[[^]]*\]/", "", $res);
   		}

	 	if( $_SESSION['navig']->formcli->raison == "" ) $res = preg_replace("/\#RAISON\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#RAISON\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->prenom == "" ) $res = preg_replace("/\#PRENOM\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#PRENOM\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->nom == "" ) $res = preg_replace("/\#NOM\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#NOM\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->adresse1 == "" ) $res = preg_replace("/\#ADRESSE1\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#ADRESSE1\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->adresse2 == "" ) $res = preg_replace("/\#ADRESSE2\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#ADRESSE2\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->adresse3 == "" ) $res = preg_replace("/\#ADRESSE3\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#ADRESSE3\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->cpostal == "" ) $res = preg_replace("/\#CPOSTAL\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#CPOSTAL\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->ville == "" ) $res = preg_replace("/\#VILLE\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#VILLE\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->pays == "" ) $res = preg_replace("/\#PAYS\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#PAYS\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->email == "") $res = preg_replace("/\#EMAIL\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#EMAIL\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->motdepasse == "") $res = preg_replace("/\#MOTDEPASSE\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#MOTDEPASSE\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->telfixe == "") $res = preg_replace("/\#TELFIXE\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#TELFIXE\[[^]]*\]/", "", $res);

	 	if( $_SESSION['navig']->formcli->telport == "") $res = preg_replace("/\#TELPORT\[([^]]*)\]/", "\\1", $res);
	 	else $res = preg_replace("/\#TELPORT\[[^]]*\]/", "", $res);

		$tmpparrain = new Client();
		$tmpparrain->charger_id($_SESSION['navig']->formcli->parrain);

		$res = str_replace("#ENTREPRISE", $_SESSION['navig']->formcli->entreprise, $res);
		$res = str_replace("#PRENOM", $_SESSION['navig']->formcli->prenom, $res);
		$res = str_replace("#NOM", $_SESSION['navig']->formcli->nom, $res);
		$res = str_replace("#TELFIXE", $_SESSION['navig']->formcli->telfixe, $res);
		$res = str_replace("#TELPORT", $_SESSION['navig']->formcli->telport, $res);
		$res = str_replace("#EMAIL", $_SESSION['navig']->formcli->email, $res);
		$res = str_replace("#ADRESSE1", $_SESSION['navig']->formcli->adresse1, $res);
		$res = str_replace("#ADRESSE2", $_SESSION['navig']->formcli->adresse2, $res);
		$res = str_replace("#ADRESSE3", $_SESSION['navig']->formcli->adresse3, $res);
		$res = str_replace("#CPOSTAL", $_SESSION['navig']->formcli->cpostal, $res);
		$res = str_replace("#VILLE", $_SESSION['navig']->formcli->ville, $res);
		$res = str_replace("#PARRAIN", $tmpparrain->email, $res);
		$res = str_replace("#PAYS", $_SESSION['navig']->formcli->pays, $res);
		$res = str_replace("#SIRET", $_SESSION['navig']->formcli->siret, $res);
		$res = str_replace("#INTRACOM", $_SESSION['navig']->formcli->intracom, $res);

		if($_SESSION['navig']->formcli->raison == ""){
		     $res = str_replace(array("#RAISON0","#RAISON1","#RAISON2","#RAISON3"),array("selected=\"selected\"","","",""), $res);
		}
		else if($_SESSION['navig']->formcli->raison == "1"){
		     $res = str_replace(array("#RAISON0","#RAISON1","#RAISON2","#RAISON3"),array("","selected=\"selected\"","",""), $res);
			 $res = str_replace(array("#CHECK1","#CHECK2","#CHECK3"),array("checked","",""), $res);
		}
		else if($_SESSION['navig']->formcli->raison == "2"){
		     $res = str_replace(array("#RAISON0","#RAISON1","#RAISON2","#RAISON3"),array("","","selected=\"selected\"",""), $res);
			 $res = str_replace(array("#CHECK1","#CHECK2","#CHECK3"),array("","checked",""), $res);
		}
		else if($_SESSION['navig']->formcli->raison == "3"){
		     $res = str_replace(array("#RAISON0","#RAISON1","#RAISON2","#RAISON3"),array("","","","selected=\"selected\""), $res);
			 $res = str_replace(array("#CHECK1","#CHECK2","#CHECK3"),array("","","checked"), $res);
		}

		$res = preg_replace("/\#EXISTE\[[^]]*\]/", "", $res);

		return $res;
	}

	function post($res){

		// Traitement de #HEADER{}
		if (preg_match_all('/#HEADER{([^}]+)}/', $res, $matches, PREG_SET_ORDER))
		{
			foreach($matches as $match)
			{
				$res = str_replace($match[0], '', $res);

				header($match[1]);
			}
		}


		if (self::get_variable(self::PREFIXE.'_show_time'))
		{
			$res = str_ireplace('</html>', '<!-- Page parsÃ©e et Ã©valuÃ©e en '.round(self::$parse_time, 4)." secondes -->\n</html>", $res);
		}

		if (Analyse::$debug_text)
		{
			$res = str_ireplace('<body>', '<body>\n' . Analyse::$debug_text, $res);
		}

		return $res;
	}

	function microtime_float(){
	   list($usec, $sec) = explode(" ", microtime());
	   return ((float)$usec + (float)$sec);
	}

	//-- Outils ----------------------------------------------------------------

    public static function get_variable($nom)
    {
        $var = new Variable();

        if ($var->charger($nom))
        {
            return $var->valeur;
        }

        return false;
    }

    protected static function create_variable($nom, $valeur)
    {
        $variable = new Variable();
		if($variable->charger($nom))
			return 0;

        $variable->nom = $nom;
        $variable->valeur = $valeur;
        $variable->protege = 1;
        $variable->cache = 1;

        $variable->add();
    }

    public static function set_variable($nom, $valeur)
    {
        $variable = new Variable();

        if ($variable->charger($nom))
        {
        	$variable->valeur = $valeur;

        	$variable->maj();

        	// Cache bug for 1.4.3.x
        	if (class_exists('CacheBase')) CacheBase::getCache()->reset_cache();
        }
    }

    protected static function delete_variable($nom)
    {
        $variable = new Variable();

        if ($variable->charger($nom)) $variable->delete();
    }

}

// Activation des traces
define ('DEBUG_PARSER', isset($_REQUEST['debug_parser']));
define ('DEBUG_EVAL'  , isset($_REQUEST['debug_eval']));

?>